package servlet;

import model.User;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/login.do")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userTypeParam = request.getParameter("userType");

//        // 确保userTypeParam不为空
//        if (userTypeParam == null || userTypeParam.isEmpty()) {
//            response.sendRedirect("login/login_errorpage.jsp");
//            return;
//        }

        int userType= Integer.parseInt(userTypeParam);


        UserService userService = new UserService();
        User user = null;

        // 根据用户角色不同进行登录验证
        switch (userType) {
            case 0: // 买家登录
                user = userService.buyerLogin(username, password);
                break;
            case 1: // 卖家登录
                user = userService.sellerLogin(username, password);
                break;
            case 2: // 管理员登录
                user = userService.managerLogin(username, password);
                break;
            default:
                // 处理角色不合法的情况
                response.sendRedirect("login/login_errorpage.jsp");
                return;
        }

        if (user != null) {
            // 登录成功，设置Session属性
            HttpSession session = request.getSession();
            session.setAttribute("user_id", Integer.toString(user.getId()));
            session.setAttribute("role", Integer.toString(user.getUser_type()));
            session.setAttribute("username", username);
            session.setAttribute("email", user.getEmail());
            session.setAttribute("phone", user.getPhone());
            session.setAttribute("gender", user.getCreated_at());

            // 根据角色重定向到不同的页面
            switch (userType) {
                case 0: // 买家
                    response.sendRedirect("Front/index.jsp"); // 根据需求填写买家登录成功后的页面
                    break;
                case 1: // 卖家
                    response.sendRedirect("background1/user/home.jsp"); // 卖家登录成功后的页面
                    break;
                case 2: // 管理员
                    response.sendRedirect("background1/admin/home.jsp"); // 管理员登录成功后的页面
                    break;
                default:
                    response.sendRedirect("login/login_errorpage.jsp");
                    break;
            }
        } else {
            // 密码错误或用户不存在，跳转到登录失败页面
            response.sendRedirect("login/login_errorpage.jsp");
        }
    }
}
